import * as ActionTypes from "./mutation-types";
import constants from "@/constants/index.js";
import config from "@/config";
import API from "@/request";
import state from "./state";
export default {
  /**
   * @description: 商品购买列表
   * @param {type}
   * @return:
   */
  [ActionTypes.ADD_BUYLIST]({ commit }, payload) {
    commit(ActionTypes.ADD_BUYLIST, payload);
  },

  /**
   * @description: 订单页面 选择地址 记录一下
   * @param {type}
   * @return:
   */
  [ActionTypes.ADD_SELECT_ADDRESS]({ commit }, payload) {
    commit(ActionTypes.ADD_SELECT_ADDRESS, payload);
  },

  /**
   * @description: 失败的异步队列
   * @param {type}
   * @return:
   */
  [ActionTypes.ADD_PROMISEQUEUE]({ commit }, payload) {
    commit(ActionTypes.ADD_PROMISEQUEUE, payload);
  },
  
  /**
   * @description 获取鉴权token
   * */
  [ActionTypes.GET_TOKEN]({ dispatch }) {
	uni.login({
		success: async function({ code } = {}) {
			if (code) {
				const response = await API.getToken({
				  code: code,
				  merchantId: config.merchantId
				});
				
				uni.setStorageSync(constants.TOKEN, response.data.token)
				uni.setStorageSync(constants.CUSTOMERID, response.data.customerId)
				uni.setStorageSync(constants.CUSTOMERROLE, response.data.role)
				uni.setStorageSync(constants.UPDATE_HAS_AGENTOR, response.data.isHasAgentor)
				
				dispatch(ActionTypes.UPDATE_CUSTOMER_ID, response.data.customerId);
				dispatch(ActionTypes.UPDATE_HAS_AGENTOR, response.data.isHasAgentor)
			}
		}
	})
  },
  
	[ActionTypes.USER_LOGIN]({ dispatch, state }, { desc = '用于完善会员资料', callBack } = {}) {
		const { islogin } = state.USER || { isLogin: false }

		if (islogin) {
			typeof callBack === "function" && callBack(state.USER);
		} else {
			uni.getUserProfile({
				desc,
				success: async function(result) {
					// console.log(result, 'result')
					const { avatarUrl, nickName, gender } = result.userInfo;
					const response = await API.login({
						avatarUrl,
						gender,
						nickName
					})
					// console.log(response, 'update member info')
					// 记录本地存储
					const userInfo = Object.assign(
						{
						  role: uni.getStorageSync(constants.CUSTOMERROLE) || 1,
						  isHasAgentor: uni.getStorageSync(constants.UPDATE_HAS_AGENTOR) || '0',
						  islogin: true,
						},
						result.userInfo
					);
					uni.setStorageSync(constants.USERINFOBYWEIXIN, userInfo);
					
					dispatch(
						ActionTypes.ADD_USERINFO,
						Object.assign(
						    {},
						    {
								username: nickName,
								face: avatarUrl,
								signature: "今人不见古时月，今月曾经照古人。",
								role: userInfo.role,
								islogin: true,
						    }
						)
					);
					
					typeof callBack === "function" && callBack(userInfo);
				},
				fail(err) {
					console.log(err, 'user_login_err')
				}
			})
		}
	},
	
	[ActionTypes.USER_LOGOUT]({ commit }) {
		commit(ActionTypes.USER_LOGOUT)
	},
	
	[ActionTypes.UPDATE_MALL_OWNER]({ commit }, userInfo) {
		uni.setStorageSync(constants.MALLOWNER, userInfo)
		commit(ActionTypes.UPDATE_MALL_OWNER, userInfo)
	},
	
	[ActionTypes.UPDATE_HAS_AGENTOR]({ commit }, val) {
		commit(ActionTypes.UPDATE_HAS_AGENTOR, val)
	},
  /**
   * @description: 用户登录的方法
   * @param {type}
   * callback 传入object
   * my.vue | productDetail.vue
   * @return:
   */
  // [ActionTypes.USER_LOGIN]({ dispatch }, { params, callBack }) {
  //   /**
  //    * 见官方：不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
  //    * https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html
  //    * 在页面产生点击事件（例如 button 上 bindtap 的回调中）后才可调用
  //    */

  //   // new logic begin
  //   uni.login({
  //     success: async function (result) {
  //       const { code } = result;

  //       const { avatarUrl, nickName, gender } = params.userInfo;
  //       const response = await API.login({
  //         code: code,
  //         merchantId: config.merchantId,
  //         avatarUrl,
  //         nickName,
  //         gender,
  //       });

  //       // 记录本地存储
  //       const userInfo = Object.assign(
  //         {
  //           role: +response.data.role || 1,
  //           islogin: true,
  //         },
  //         params.userInfo
  //       );

  //       uni.setStorageSync(constants.USERINFOBYWEIXIN, userInfo);
  //       uni.setStorageSync(constants.TOKEN, response.data.token);
  //       uni.setStorageSync(constants.CUSTOMERID, response.data.customerId);

  //       // 这里更新下用户id
  //       dispatch(ActionTypes.UPDATE_CUSTOMER_ID, response.data.customerId);

  //       dispatch(
  //         ActionTypes.ADD_USERINFO,
  //         Object.assign(
  //           {},
  //           {
  //             username: nickName,
  //             face: avatarUrl,
  //             signature: "今人不见古时月，今月曾经照古人。",
  //             role: +response.data.role || 1,
  //             islogin: true,
  //           }
  //         )
  //       );

  //       typeof callBack === "function" && callBack();
  //       // new logic end

  //       // old logic start
  //       // 使用getUserInfo
  //       // uni.getUserProfile({
  //       //   provider: "weixin",
  //       //   success: async (result) => {
  //       //     console.log("getUserInfo success", result);
  //       //     const { avatarUrl, nickName, gender } = result.userInfo;
  //       //     const response = await API.login({
  //       //       code: code,
  //       //       merchantId: config.merchantId,
  //       //       avatarUrl,
  //       //       nickName,
  //       //       gender,
  //       //     });
  //       //     // console.log(response, 'response -----')
  //       //     // 记录本地存储
  //       //     const userInfo = Object.assign(
  //       //       {
  //       //         role: +response.data.role || 1,
  //       //         islogin: true,
  //       //       },
  //       //       result.userInfo
  //       //     );

  //       //     uni.setStorageSync(constants.USERINFOBYWEIXIN, userInfo);
  //       //     uni.setStorageSync(constants.TOKEN, response.data.token);
  //       //     uni.setStorageSync(constants.CUSTOMERID, response.data.customerId);

  //       //     // 这里更新下用户id
  //       //     dispatch(ActionTypes.UPDATE_CUSTOMER_ID, response.data.customerId);

  //       //     dispatch(
  //       //       ActionTypes.ADD_USERINFO,
  //       //       Object.assign(
  //       //         {},
  //       //         {
  //       //           username: nickName,
  //       //           face: avatarUrl,
  //       //           signature: "今人不见古时月，今月曾经照古人。",
  //       //           role: +response.data.role || 1,
  //       //           islogin: true,
  //       //         }
  //       //       )
  //       //     );

  //       //     typeof callBack === "function" && callBack(userInfo);
  //       //   },
  //       //   fail: (error) => {
  //       //     console.log("getUserInfo fail", error);
  //       //   },
  //       // });
  //       // old logic end
  //     },
  //   });
  // },

  /**
   * @description: 添加用户微信信息
   * @param {type}
   * @return:
   */
  [ActionTypes.ADD_USERINFO]({ commit }, payload) {
    commit(ActionTypes.ADD_USERINFO, payload);
  },

  /**
   * @description: 更新用户ID
   * @param {type}
   * @return:
   */
  [ActionTypes.UPDATE_CUSTOMER_ID]({ commit }, payload) {
    commit(ActionTypes.UPDATE_CUSTOMER_ID, payload);
  },

  /**
   * @description 更新用户的角色
   */
  [ActionTypes.UPDATE_USER_ROLE]({ commit }, payload) {
    commit(ActionTypes.UPDATE_USER_ROLE, payload);
  },

  /**
   * @description: 用户支付的公共方法
   * @param { orderId:String, callBack:Function }
   * @return:
   */
  async [ActionTypes.USER_PAY](
    { commit },
    { orderId, success, fail, callBack }
  ) {
    let { data } = await API.pay(orderId);
    data = JSON.parse(data);

    uni.showToast({
      duration: 10000000,
      title: "正在加载...",
      icon: "loading",
    });

    uni.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      paySign: data.sign,
      signType: data.signType,
      complete(data) {
        typeof callBack === "function" && callBack(data);
        // uni.hideToast()
      },
      success(data) {
        typeof success === "function" && success(data);
      },
      fail(data) {
        // uni.showToast({
        // 	title:'支付失败',
        // 	icon: 'none'
        // })
        typeof fail === "function" && fail(data);
      },
    });
  },

  /**
   * @description: 更新进入商品分类的时候携带的参数
   * @param {type}
   * @return:
   */
  async [ActionTypes.CLASSIFY_PAGES_PARAMS]({ commit }, payload) {
    commit(ActionTypes.CLASSIFY_PAGES_PARAMS, payload);
  },

  /**
   * @description: 获取首页商品列表
   * @param {type}
   * @return:
   */
  async [ActionTypes.GET_PRODUCTS_LIST]({ commit }) {
    let response = await API.GetProductListByHome({
      merchantId: state.merchantId,
      pageSize: 10,
    });

    commit(ActionTypes.GET_PRODUCTS_LIST, response.data);
  },

  /**
   * @description 设置系统信息
   */
  [ActionTypes.SET_SYSTEM_INFO]({ commit }, payload) {
    commit(ActionTypes.SET_SYSTEM_INFO, payload);
  },
};
